var config = parent.parent.CONFIG,system=parent.parent.SYSTEM;
var isRefresh = false;
var _limitMenu = system.MENULIMIT.SELL25;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'sell/coupon/page';

var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/to_list_sub_dialog',
			data : {multiselect:false},
			width : 450,
			height : 370,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#sc_shop_code").val(selected.sp_code);
					$("#shop_name").val(selected.sp_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	operate: function(oper, id){//修改、新增
		if(oper == 'add'){
			url = config.BASEPATH+"sell/coupon/to_add";
			data = {oper: oper, callback:this.callback};
		}else if(oper == 'edit'){
			url = config.BASEPATH+"sell/coupon/to_update?sc_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'view'){
			url = config.BASEPATH+"sell/coupon/to_view?sc_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'approve'){
			url = config.BASEPATH+"sell/coupon/to_view?sc_id="+id;
			data = {oper: oper,callback: this.callback};
		}else{
			return false;
		}
		$.dialog({
			title : false,
			content : 'url:'+url,
			data: data,
			max : false,
			min : false,
			cache : false,
			lock: false,
			close:function(){
		   		if(isRefresh){
		   			THISPAGE.reloadData();
			   	}
		   	}
		}).max();
	},
	del: function(rowId){//删除
		if(rowId != null && rowId != ''){
			var rowData = $("#grid").jqGrid("getRowData", rowId);
		 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
				$.ajax({
					type:"POST",
					url:config.BASEPATH+'sell/coupon/del',
					data:{"sc_number":rowData.sc_number},
					cache:false,
					dataType:"json",
					success:function(data){
						if(undefined != data && data.stat == 200){
							Public.tips({type: 3, content : '删除成功!'});
							$('#grid').jqGrid('delRowData', rowId);
						}else{
							Public.tips({type: 1, content : data.message});
						}
					}
				});
			});
	   }else{
		   Public.tips({type: 1, content : '请选择数据!'});
	   }	
    },
	operFmatter : function(val, opt, row){
		var btnHtml = '';
		if (row.sc_state == '0') {
            btnHtml += '<input type="button" value="审核" class="btn_sp" onclick="javascript:handle.operate(\'approve\',' + opt.rowId + ');" />';
        } else if (row.sc_state == '1') {
            btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
        } else if (row.sc_state == '2') {
        	var log_user = $("#log_user").val();
        	if(row.sc_us_id == log_user){
        		btnHtml += '<input type="button" value="修改" class="btn_xg" onclick="javascript:handle.operate(\'edit\',' + opt.rowId + ');" />';
        	}else{
        		btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
        	}
        } else {
        	btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
        }
		btnHtml += '<input type="button" value="流程" class="btn_qh" onclick="javascript:listBillProcess(\''+row.sc_number+'\',\'t_sell_coupon\');" />';
		return btnHtml;
	},
	formatMoney:function(val, opt, row){
		var moneyHtml = "满";
		moneyHtml += row.sc_full_money;
		moneyHtml += "元/减";
		moneyHtml += row.sc_minus_money;
		moneyHtml += "元";
		return moneyHtml;
	},
	formatType:function(val, opt, row){//0.全场1.类别2.品牌3商品
		if(val == 0){
			return '全场';
		}else if(val == 1){
			return '类别';
		}else if(val == 2){
			return '品牌';
		}else if(val == 3){
			return '商品';
		}
		return val;
	},
	formatDate:function(val, opt, row){
		var dateHtml = row.sc_begindate;
		dateHtml += "~";
		dateHtml += row.sc_enddate;
		return dateHtml;
	},
	formatLastAmount:function(val, opt, row){
		var amount = row.sc_amount-row.sc_receive_amount;
		return amount;
	},
	formatState:function(val, opt, row){//0：未审核；1：已审核2：已退回
		if(val == 0){
			return '未审核';
		}else if(val == 1){
			return '已审核';
		}else if(val == 2){
			return '已退回';
		}else if(val == 4){
			return '已终止';
		}
		return val;
	}
};
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		this.$_ar_state = $("#ar_state").cssRadio({ callback: function($_obj){
			$("#sc_state").val($_obj.find("input").val());
		}});
		this.$_type = $("#type").cssRadio({ callback: function($_obj){
			$("#sc_type").val($_obj.find("input").val());
		}});
	},
	initGrid:function(){
		var gridWH = Public.setGrid();
		var colModel = [
	    	{name: 'operate',label:'操作',width: 100, formatter: handle.operFmatter,align:'center', sortable:false},
	    	{name: 'sc_shop_name',label:'发放店铺',index:'sc_shop_name',width: 100,title:true},
	    	{name: 'sc_number',label:'单据编号',index: 'sc_number',width:180},
	    	{name: 'sc_makedate',label:'制单日期',index: 'sc_makedate',width:80},
	    	{name: 'sc_name',label:'方案名称',index: 'sc_name',width:120},
	    	{name: 'sc_full_money',label:'满/减规格',index:'sc_full_money',width: 140, title: false,formatter: handle.formatMoney},
	    	{name: 'sc_minus_money',label:'减多少元',index:'sc_minus_money',hidden:true},
	    	{name: 'sc_type',label:'使用范围',index: 'sc_type',width:60,formatter: handle.formatType},
	    	{name: 'sc_begindate',label:'有效期限',index: 'sc_begindate',width:170,formatter: handle.formatDate},
	    	{name: 'sc_amount',label:'发布数量',index:'sc_amount',width:70, title: false,align:'right'},    	
	    	{name: 'sc_receive_amount',label:'领取数量',index:'sc_receive_amount',width:70,title: false,align:'right'},
	    	{name: 'sc_last_amount',label:'剩余数量',index:'sc_last_amount',width:70,title: false,align:'right',formatter: handle.formatLastAmount},
	    	{name: 'sc_state',label:'状态',index:'sc_state',width:80,formatter: handle.formatState},
	    	{name: 'sc_remark',label:'使用说明',index:'sc_remark',width: 150,align:'left'},
	    	{name: 'sc_us_id',label:'创建用户id',index:'sc_us_id',hidden:true}
	    ];
		$('#grid').jqGrid({
            url:queryurl,			
			datatype: 'json',
			width: gridWH.w-12,
			height: gridWH.h-20,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id: 'sc_id'  //图标ID
			},
			loadComplete: function(data){
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	buildParams : function(){
		var params = '';
		params += 'begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&sc_state='+$("#sc_state").val();
		params += '&sc_type='+$("#sc_type").val();
		params += '&sc_shop_code='+$("#sc_shop_code").val();
		params += '&sc_name='+Public.encodeURI($("#sc_name").val());
		params += '&sc_number='+Public.encodeURI($("#sc_number").val());
		return params;
	},
	reset:function(){
		$("#shop_name").val("");
		$("#sc_shop_code").val("");
		$("#sc_name").val("");
		$("#sc_number").val("");
		$("#sc_type").val("");
		$("#sc_state").val("");
		THISPAGE.$_type.setValue(0);
		THISPAGE.$_date.setValue(0);
		THISPAGE.$_ar_state.setValue(0);
		$("#begindate").val("");
		$("#enddate").val("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		//新增
		$('#btn-add').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.INSERT)) {
				return ;
			}
			handle.operate('add');
		});
		//删除
		$('#btn-del').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var rowId = $('#grid').jqGrid('getGridParam','selrow');
			if(rowId == null || rowId == ''){
				Public.tips({type: 2, content : "您未选择任何数据"});
				return;
			}
			var rowData =$("#grid").jqGrid("getRowData", rowId);
			if(rowData.ss_state == "已审核" || rowData.ss_state == "已终止"){
				Public.tips({type: 2, content : "单据已审核，不能删除"});
				return;
			}
			handle.del(rowId)
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
	}
}
THISPAGE.init();